import Vue from 'vue'
import Router from 'vue-router'
import login from "../views/login";
import register from "../views/register";
import index from "../views/index";
import personalView from "../views/personal/personalView";
import Cookies from 'js-cookie'; //引入cookie操作依赖


Vue.use(Router)

const router = new Router({
  mode: 'history',
  base: process.env.BASE_URL,
  routes :[
    {
      path: '/',
      name: 'login',
      component: login,
    },
    {
      path: '/register',
      name: 'register',
      component: register
    },
    {
      path: '/personal',
      name: 'personal',
      component: personalView,
      meta: {requireAuth:true}
    },
    {
      path: '/index',
      component: index,
      meta: {requireAuth:true},
      children: [
        {
          path: '',
          component: (resolve) => require(['../views/basic/PetView.vue'], resolve),
          meta: {requireAuth:true}

        },
        {
          path: "user",
          component: (resolve) => require(['../views/basic/UserView.vue'], resolve),
          meta: {requireAuth:true}
        },
        {
          path: "order",
          component: (resolve) => require(['../views/basic/OrderView.vue'], resolve),
          meta: {requireAuth:true}
        },
        {
          path: "sql",
          component: (resolve) => require(['../views/monitor/sqlMonitor.vue'], resolve),
          meta: {requireAuth:true}
        },
        {
          path: "swagger",
          component: (resolve) => require(['../views/monitor/swaggerMonitor.vue'], resolve),
          meta: {requireAuth:true}
        },
        {
          path: "chart",
          component: (resolve) => require(['../views/chart/chartView.vue'], resolve),
          meta: {requireAuth:true}
        },
        {
          path: "permission",
          component: (resolve) => require(['../views/basic/permissionView.vue'], resolve),
          meta: {requireAuth:true}
        },
        {
          path: "hot",
          component: (resolve) => require(['../views/sysytem/hotView.vue'], resolve),
          meta: {requireAuth:true}
        },
        ]
    },
    {
      path: '*',
      name: 'error',
      component: (resolve) => require(['../views/errors/404.vue'], resolve)
    },

  ]
})

router.beforeEach((to, from, next) => {
  if (to.meta.requireAuth) { // 判断该路由是否需要登录权限
    if(Cookies.get('authorization')){ //判断Cookie是否存在access_token
      next();
    }else {
      if(to.path === '/'){
        next();
      }else {
        alert('请先进行登录！')
        next({
          path:'/'
        })
      }
    }
  }
  else {
    next();
  }
  /*如果本地 存在 token 则 不允许直接跳转到 登录页面*/
  // if(to.fullPath == "/"){
  //   if(Cookies.get('authorization')){
  //     alert('您已经登录了，如果想要登录其他账号，请先退出当前账号！')
  //     next({
  //       path:from.fullPath
  //     });
  //   }else {
  //     next();
  //   }
  // }
});


export default router


